<template>
  <view class="appointment-manage-container">
    <!-- 顶部状态筛选系统 -->
    <view class="status-filter">
      <view :class="['status-item', { 'active': currentStatus === 'all' }]" @tap="filterByStatus('all')">
        <text>全部</text>
      </view>
      <view :class="['status-item', { 'active': currentStatus === 'pending' }]" @tap="filterByStatus('pending')">
        <text>待就诊</text>
        <uni-badge v-if="unreadCount > 0" :text="unreadCount" type="error" size="small"></uni-badge>
      </view>
      <view :class="['status-item', { 'active': currentStatus === 'completed' }]" @tap="filterByStatus('completed')">
        <text>已完成</text>
      </view>
      <view :class="['status-item', { 'active': currentStatus === 'cancelled' }]" @tap="filterByStatus('cancelled')">
        <text>已取消</text>
      </view>
    </view>

    <!-- 预约记录列表 -->
    <scroll-view scroll-y class="appointment-list-scroll" v-if="filteredAppointments.length > 0">
      <view class="appointment-card" v-for="appointment in filteredAppointments" :key="appointment.appointmentId">
        <view :class="['status-bar', getStatusColor(appointment.status, appointment.appointmentDate)]"></view>
        <view class="card-content">
          <view class="info-section">
            <text class="hospital-name">{{ appointment.hospitalName }}</text>
            <text class="department-name">{{ appointment.departmentName }}</text>
          </view>
          <view class="info-section">
            <text class="doctor-info">{{ appointment.doctorName }} {{ appointment.doctorJobTitle }}</text>
            <text class="doctor-specialty">{{ appointment.doctorProfessionalExpertise }}</text>
          </view>
          <view class="info-section time-info">
            <text class="appointment-date">{{ appointment.appointmentDate }}</text>
            <text class="appointment-time">{{ appointment.appointmentTimeSlot }}</text>
            <text class="appointment-id">编号: {{ appointment.appointmentId }}</text>
          </view>
          
          <!-- 操作按钮 -->
          <view class="action-buttons">
            <button class="action-btn" @tap="viewDetails(appointment)">详情</button>
            <button class="action-btn" v-if="appointment.status === '待确认' || appointment.status === '已确认'" @tap="rescheduleAppointment(appointment)">改签</button>
            <button class="action-btn" v-if="appointment.status === '待确认' || appointment.status === '已确认'" @tap="cancelAppointment(appointment)">取消</button>
            <button class="action-btn" v-if="appointment.status === '已完成'" @tap="rebookAppointment(appointment)">再次预约</button>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 智能空状态提示 -->
    <view class="empty-state" v-else>
      <image src="/static/img/calendar_icon.png" class="empty-icon"></image>
      <text class="empty-text">暂无预约记录</text>
      <button class="primary-btn" @tap="goToAppointmentPage">立即预约</button>
    </view>

    <!-- 取消预约确认弹窗 -->
    <uni-popup ref="cancelConfirmPopup" type="center">
      <view class="confirm-modal">
        <text class="modal-title">取消预约</text>
        <text class="modal-content">确定要取消本次预约吗？</text>
        <text class="modal-tip" v-if="isWithin24Hours">注意：24小时内取消可能会产生手续费。</text>
        <view class="modal-buttons">
          <button class="cancel-btn" @tap="closeCancelConfirm">暂不取消</button>
          <button class="confirm-btn" @tap="confirmCancel">确认取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { listAppointment, getAppointment, updateAppointmentStatus } from '@/api/appointment.js';
import { getHospital } from '@/api/hospital.js';
import { getDepartment } from '@/api/department.js';
import { getInfoDoctor } from '@/api/doctor.js';

export default {
  components: {
    // uni-badge 和 uni-popup 应该在 easycom 配置中自动引入，如果不行，需要手动在这里或全局注册
  },
  data() {
    return {
      currentStatus: 'all', // 全部, pending, completed, cancelled
      allAppointments: [], // 存储所有预约记录
      unreadCount: 0, // 待就诊的未读数量
      selectedAppointmentToCancel: null, // 待取消的预约对象
      isWithin24Hours: false, // 是否在24小时内
    };
  },
  computed: {
    filteredAppointments() {
      if (this.currentStatus === 'all') {
        return this.allAppointments;
      } else if (this.currentStatus === 'pending') {
        // 待就诊包含 '待确认' 和 '已确认' 两种状态
        return this.allAppointments.filter(app => app.status === '待确认' || app.status === '已确认');
      } else if (this.currentStatus === 'completed') {
        // 已完成状态
        return this.allAppointments.filter(app => app.status === '已完成');
      } else if (this.currentStatus === 'cancelled') {
        // 已取消状态
        return this.allAppointments.filter(app => app.status === '已取消');
      } else {
        return []; // 未知状态返回空数组
      }
    },
  },
  onShow() {
    this.fetchAppointments(); // 页面显示时刷新数据
  },
  methods: {
    async fetchAppointments() {
      try {
        // 传递分页参数，确保获取所有数据
        const res = await listAppointment({ pageNum: 1, pageSize: 200 }); // 假设 pageSize 足够大以获取所有数据
        console.log('listAppointment API Response:', res); // 添加这行日志
        if (res.code === 200 && res.rows) {
          // 补充医院、科室、医生信息，并进行状态处理
          this.allAppointments = await Promise.all(res.rows.map(async app => {
            const hospital = await getHospital(app.hospitalId);
            const department = await getDepartment(app.departmentId);
            const doctor = await getInfoDoctor(app.doctorId);

            console.log('Processing Appointment Status:', app.status); // 添加这行日志

            return {
              ...app,
              hospitalName: hospital.data ? hospital.data.name : '未知医院',
              departmentName: department.data ? department.data.name : '未知科室',
              doctorName: doctor.data ? doctor.data.name : '未知医生',
              doctorJobTitle: doctor.data ? doctor.data.jobTitle : '',
              doctorProfessionalExpertise: doctor.data ? doctor.data.professionalExpertise : '',
            };
          }));
          this.updateUnreadCount(); // 更新未读数量
          console.log('Fetched Appointments (Processed):', this.allAppointments);
        } else {
          this.allAppointments = [];
          console.log('No appointment data received or API error.', res); // 添加这行日志
        }
      } catch (error) {
        console.error('获取预约记录失败:', error);
        this.allAppointments = [];
      }
    },
    updateUnreadCount() {
      this.unreadCount = this.allAppointments.filter(app => app.status === '待就诊').length;
    },
    filterByStatus(status) {
      this.currentStatus = status;
    },
    getStatusColor(status, appointmentDate) {
      const today = new Date().toISOString().slice(0, 10);
      if (status === '待就诊') {
        if (appointmentDate === today) {
          return 'status-bar-red'; // 今日就诊
        } else {
          return 'status-bar-blue'; // 待就诊
        }
      } else if (status === '已完成') {
        return 'status-bar-green'; // 已完成
      } else if (status === '已取消') {
        return 'status-bar-grey'; // 已取消
      } else {
        return ''; // 默认
      }
    },
    viewDetails(appointment) {
      uni.navigateTo({
        url: `/pages/appointment/detail?id=${appointment.appointmentId}` // 假设有一个详情页
      });
      // 在这里添加查看详情的逻辑
    },
    rescheduleAppointment(appointment) {
      uni.navigateTo({
        url: '/pages/appointment/index' // 直接导航到预约挂号页面
      });
    },
    cancelAppointment(appointment) {
      this.selectedAppointmentToCancel = appointment;
      // 判断是否在24小时内，这里需要更精确的日期时间计算
      const appointmentDateTime = new Date(`${appointment.appointmentDate} ${appointment.appointmentTimeSlot.split('-')[0]}`);
      const now = new Date();
      const diffHours = Math.abs(appointmentDateTime.getTime() - now.getTime()) / (1000 * 60 * 60);
      this.isWithin24Hours = diffHours < 24;

      this.$refs.cancelConfirmPopup.open();
    },
    closeCancelConfirm() {
      this.$refs.cancelConfirmPopup.close();
      this.selectedAppointmentToCancel = null;
    },
    async confirmCancel() {
      if (!this.selectedAppointmentToCancel) return;
      try {
        // 调用新的接口来更新预约状态为"已取消"
        const res = await updateAppointmentStatus(this.selectedAppointmentToCancel.appointmentId, '已取消');
        if (res.code === 200) {
          uni.showToast({
            title: '预约已取消',
            icon: 'success'
          });
          this.closeCancelConfirm();
          this.fetchAppointments(); // 刷新列表
        } else {
          uni.showToast({
            title: res.msg || '取消失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('取消预约失败:', error);
        uni.showToast({
          title: '取消预约请求失败',
          icon: 'none'
        });
      }
    },
    rebookAppointment(appointment) {
      uni.navigateTo({
        url: '/pages/appointment/index'
      });
    },
    goToAppointmentPage() {
      uni.navigateTo({
        url: '/pages/appointment/index' // 导航到预约挂号页面
      });
    },
  },
};
</script>

<style scoped>
/* 整体容器 */
.appointment-manage-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: 20rpx; /* 底部留白 */
}

/* 状态筛选 */
.status-filter {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.status-item {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  font-size: 30rpx;
  color: #666;
  position: relative;
}

.status-item.active {
  color: #4B7BFF;
  font-weight: bold;
}

.status-item.active::after {
  content: '';
  position: absolute;
  bottom: -10rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 60%;
  height: 6rpx;
  background-color: #4B7BFF;
  border-radius: 3rpx;
}

/* 预约记录列表 */
.appointment-list-scroll {
  flex: 1;
  padding: 20rpx;
}

.appointment-card {
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  overflow: hidden; /* 确保色条不会溢出 */
  display: flex;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.05);
}

.status-bar {
  width: 16rpx;
  flex-shrink: 0;
}

.status-bar-blue {
  background-color: #4B7BFF; /* 待就诊 */
}

.status-bar-red {
  background-color: #FF4D4F; /* 今日就诊 */
}

.status-bar-green {
  background-color: #52C41A; /* 已完成 */
}

.status-bar-grey {
  background-color: #BFBFBF; /* 已取消 */
}

.card-content {
  flex: 1;
  padding: 20rpx 30rpx;
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.info-section {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  flex-wrap: wrap; /* 允许信息换行 */
}

.hospital-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-right: 15rpx;
}

.department-name {
  font-size: 28rpx;
  color: #666;
}

.doctor-info {
  font-size: 28rpx;
  font-weight: bold;
  margin-right: 15rpx;
}

.doctor-specialty {
  font-size: 24rpx;
  color: #999;
}

.time-info .appointment-date,
.time-info .appointment-time {
  font-size: 28rpx;
  color: #4B7BFF;
  font-weight: bold;
  margin-right: 15rpx;
}

.appointment-id {
  font-size: 24rpx;
  color: #999;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 20rpx;
}

.action-btn {
  flex: 1; /* 自动分配宽度 */
  min-width: 160rpx; /* 最小宽度，防止过窄 */
  height: 60rpx;
  line-height: 60rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
  text-align: center;
  background-color: #f0f0f0;
  color: #666;
  border: none;
  padding: 0 10rpx;
  transition: background-color 0.2s ease;
}

.action-btn:active {
  background-color: #e0e0e0;
}

/* 立即预约按钮样式 */
.primary-btn {
  width: 80%;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  background-color: #4B7BFF;
  color: #fff;
  font-size: 32rpx;
  margin-top: 40rpx;
  text-align: center;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
  text-align: center;
  color: #999;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  margin-bottom: 40rpx;
}

/* 确认弹窗样式 */
.confirm-modal {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  width: 600rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.modal-content {
  font-size: 30rpx;
  color: #666;
  text-align: center;
  margin-bottom: 30rpx;
}

.modal-tip {
  font-size: 26rpx;
  color: #FF4D4F; /* 红色警告 */
  margin-bottom: 40rpx;
}

.modal-buttons {
  display: flex;
  justify-content: space-around;
  width: 100%;
}

.cancel-btn,
.confirm-btn {
  width: 45%;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
  text-align: center;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #666;
}

.confirm-btn {
  background-color: #4B7BFF;
  color: #fff;
}
</style>
